#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

void writer(int fd)
{
    const char* str = "I am tired";
    char buffer[128];
    int pid = getpid();

    int cnt = 0;

    while(1)
    {
        snprintf(buffer,sizeof(buffer),"message:%s,pid:%d,cnt:%d\n",str,pid,cnt);
        write(fd,buffer,strlen(buffer));
        cnt++;
        sleep(1);
    }
}

void reader(int fd)
{
    char buffer[128];

    while(1)
    {
        read(fd,buffer,sizeof(buffer));
        printf("%s",buffer);
        
    }
}

int main()
{

    int fd[2];
    int pipe_id = pipe(fd);

    int id = fork();
    if(id == 0)
    {
        //关闭子进程的读端
        close(fd[0]);
        writer(fd[1]);
        exit(0);
    }

    close(fd[1]);
    reader(fd[0]);

    wait(NULL);

    return 0;
}